<template>
  <div class="dialog-container">


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dispatch:routeStationExtend:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dispatch:routeStationExtend:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dispatch:routeStationExtend:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routeStationExtendList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" v-if="true" />
      <el-table-column label="扩展类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="basic_device_dispatch_protocol" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改线路站点扩展对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="routeStationExtendRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="扩展类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择扩展类型">
            <el-option v-for="dict in basic_device_dispatch_protocol" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快速设置">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button size="small" type="success" plain @click="topClick">【上行】开始采集的</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button size="small" type="success" plain @click="downClick">【下行】开始采集的</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="">
          <el-table max-height="400px" v-loading="loading" :data="stations">
            <el-table-column label="站点名称" align="left" prop="stationName" />
            <el-table-column label="默认站序" align="center" prop="defaultStationOrder" />
            <el-table-column label="站序" align="center" prop="stationOrder">
              <template #default="scope">
                <el-input v-model="scope.row.stationOrder" placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="方向" align="center" prop="direction">
              <template #default="scope">
                <el-select v-model="scope.row.direction" placeholder="请选择">
                  <el-option key="1" label="上行" :value="parseInt(1)"></el-option>
                  <el-option key="2" label="下行" :value="parseInt(2)"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="默认方向" align="center" prop="defaultDirection">
              <template #default="scope">
                {{ scope.row.defaultDirection == 1 ? '上行' : '下行' }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RouteStationExtend">
import { listRouteStationExtend, getRouteStationExtend, delRouteStationExtend, addRouteStationExtend, updateRouteStationExtend } from "@/api/dispatch/routeStationExtend";
import { listRouteStation } from "@/api/basic/routeStation.js";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const { sys_data_status, basic_device_dispatch_protocol } = proxy.useDict('sys_data_status', 'basic_device_dispatch_protocol');
const props = defineProps({
  // 当前的值
  routeId: [Number, String]
});
const routeStationExtendList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    routeId: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "拓展不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询线路站点扩展列表 */
function getList() {
  loading.value = true;
  listRouteStationExtend(queryParams.value).then(response => {
    routeStationExtendList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    routeId: props.routeId,
    type: null,
    remark: null,
    status: '0',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    list: []
  };
  stations.value = [];
  proxy.resetForm("routeStationExtendRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const stations = ref([])
function getAllStations(list = []) {
  if (list.length > 0) {
    list.forEach((element, index) => {
      list[index].defaultStationOrder = element.stationOrder
      list[index].defaultDirection = element.direction
      stations.value = list;//JSON.parse(JSON.stringify(res.data));
    })
  } else {
    listRouteStation(queryParams.value).then(res => {
      res.data.forEach((element, index) => {
        res.data[index].defaultStationOrder = element.stationOrder
        res.data[index].defaultDirection = element.direction
      });
      stations.value = res.data;//JSON.parse(JSON.stringify(res.data));
    })
  }

}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加线路站点扩展";
  getAllStations();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();

  const _id = row.id || ids.value
  getRouteStationExtend(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改线路站点扩展";
    getAllStations(response.data.list);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["routeStationExtendRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      form.value.list = stations.value
      if (form.value.id != null) {
        updateRouteStationExtend(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addRouteStationExtend(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除线路站点扩展编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delRouteStationExtend(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

watch(props, (newVal, oldVal) => {
  queryParams.value.routeId = newVal.routeId
  getList()
}, { immediate: true });
function topClick() {
  stations.value.forEach((item, index) => {
    item.direction = item.direction == 1 ? 2 : 1
  })
}

import _ from 'lodash'

function downClick() {
  let result = _.countBy(stations.value, function (num) {
    return num.direction == 1;
  });
  let temp;
  let down;
  if (stations.value[0].direction == 2) {
    if (stations.value[0].stationOrder == 1) {
      down = result.true + 1;
      temp = 1;
    } else {
      down = 1;
      temp = result.false + 1;
    }
  } else {
    if (stations.value[0].stationOrder == 1) {
      temp = result.false + 1;
      down = 1;
    } else {
      temp = 1;
      down = result.true + 1;
    }
  }


  stations.value.forEach((item, index) => {
    if (item.direction == 1) {
      item.stationOrder = temp++
    } else {
      item.stationOrder = down++
    }
  })
}
</script>
